<template>
  <div class="settings-container">
    <h1 class="page-title">系统设置</h1>
    
    <el-card class="settings-card">
      <el-tabs v-model="activeTab">
        <!-- 店铺信息设置 -->
        <el-tab-pane label="店铺信息" name="store">
          <el-form :model="storeSettings" label-width="120px" v-loading="loading.store">
            <el-form-item label="店铺名称">
              <el-input v-model="storeSettings.name" placeholder="请输入店铺名称" />
            </el-form-item>
            
            <el-form-item label="店铺位置">
              <el-input v-model="storeSettings.location" placeholder="请输入店铺位置（如：国贸360店）" />
            </el-form-item>
            
            <el-form-item label="店铺地址">
              <el-input v-model="storeSettings.address" placeholder="请输入店铺地址" />
            </el-form-item>
            
            <el-form-item label="联系电话">
              <el-input v-model="storeSettings.phone" placeholder="请输入联系电话" />
            </el-form-item>
            
            <el-form-item label="营业时间">
              <el-time-picker
                v-model="storeSettings.openTime"
                format="HH:mm"
                placeholder="开始时间"
                value-format="HH:mm"
                :disabled-hours="() => []"
                :disabled-minutes="() => []"
              />
              <span class="time-separator">至</span>
              <el-time-picker
                v-model="storeSettings.closeTime"
                format="HH:mm"
                placeholder="结束时间"
                value-format="HH:mm"
                :disabled-hours="() => []"
                :disabled-minutes="() => []"
              />
            </el-form-item>
            
            <el-form-item label="税号">
              <el-input v-model="storeSettings.taxNumber" placeholder="请输入税号" />
            </el-form-item>
            
            <el-form-item label="品牌标语">
              <el-input v-model="storeSettings.slogan" placeholder="请输入品牌标语" />
            </el-form-item>

            <el-form-item label="小票二维码">
              <el-upload
                class="qrcode-uploader"
                :action="getApiUrl('/upload/qr-code')"
                :show-file-list="false"
                :on-success="handleQrCodeSuccess"
                :before-upload="beforeQrCodeUpload"
                :headers="getAuthHeaders()"
                name="file"
              >
                <template v-if="storeSettings.qrCodeUrl && storeSettings.qrCodeUrl.trim()">
                  <img :src="storeSettings.qrCodeUrl" class="qrcode-image" />
                  <div class="qrcode-overlay">
                    <el-icon class="qrcode-change-icon"><Edit /></el-icon>
                    <span>更换图片</span>
                  </div>
                </template>
                <el-icon v-else class="qrcode-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="qrcode-tip">上传小票底部显示的二维码，建议尺寸: 200px × 200px</div>
              <div v-if="storeSettings.qrCodeUrl && storeSettings.qrCodeUrl.trim()" class="qrcode-actions">
                <el-button type="text" size="small" @click="removeQrCode">
                  <el-icon><Delete /></el-icon> 删除二维码
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveStoreSettings">保存设置</el-button>
              <el-button @click="resetStoreSettings">恢复默认</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 小票打印设置 -->
        <el-tab-pane label="小票设置" name="receipt">
          <div class="receipt-settings-container">
            <div class="receipt-form">
              <el-form :model="receiptSettings" label-width="120px" v-loading="loading.receipt">
                <el-form-item label="小票宽度">
                  <el-radio-group v-model="receiptSettings.width">
                    <el-radio label="58">58mm</el-radio>
                    <el-radio label="80">80mm</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="字体大小">
                  <el-select v-model="receiptSettings.fontSize">
                    <el-option label="小" value="small" />
                    <el-option label="中" value="medium" />
                    <el-option label="大" value="large" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="页眉内容">
                  <el-input v-model="receiptSettings.header" type="textarea" :rows="2" />
                </el-form-item>
                
                <el-form-item label="页脚内容">
                  <el-input v-model="receiptSettings.footer" type="textarea" :rows="2" />
                </el-form-item>
                
                <el-form-item label="打印选项">
                  <el-checkbox v-model="receiptSettings.printLogo">打印LOGO</el-checkbox>
                  <el-checkbox v-model="receiptSettings.printQrCode">打印二维码</el-checkbox>
                  <el-checkbox v-model="receiptSettings.printOrderNumber">打印订单号</el-checkbox>
                  <el-checkbox v-model="receiptSettings.directPrint">直接打印（不显示预览）</el-checkbox>
                </el-form-item>
                
                <el-form-item label="商品显示">
                  <el-radio-group v-model="receiptSettings.productDisplay">
                    <el-radio label="simple">简洁模式</el-radio>
                    <el-radio label="detailed">详细模式</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="saveReceiptSettings">保存设置</el-button>
                  <el-button @click="printTestReceipt">打印测试</el-button>
                  <el-button @click="resetReceiptSettings">恢复默认</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="receipt-preview">
              <h3>小票预览</h3>
              <div class="receipt-preview-container" :style="{ width: receiptSettings.width + 'mm' }">
                <!-- 小票预览内容 -->
                <div class="receipt-mock">
                  <div class="receipt-header" v-if="receiptSettings.header">
                    {{ receiptSettings.header }}
                  </div>
                  <div class="receipt-title">
                    {{ storeSettings.name || '哈喽啤鲜生' }}
                  </div>
                  <div class="receipt-info">
                    <div>单号: 2023070100001</div>
                    <div>日期: {{ new Date().toLocaleString() }}</div>
                  </div>
                  <div class="receipt-items">
                    <div class="receipt-item-header">
                      <span>商品</span>
                      <span>数量</span>
                      <span>单价</span>
                      <span>金额</span>
                    </div>
                    <div class="receipt-item">
                      <span>比利时小麦</span>
                      <span>2</span>
                      <span>¥15.00</span>
                      <span>¥30.00</span>
                    </div>
                    <div class="receipt-item">
                      <span>原浆鲜啤</span>
                      <span>1</span>
                      <span>¥18.00</span>
                      <span>¥18.00</span>
                    </div>
                  </div>
                  <div class="receipt-total">
                    <div>总计: ¥48.00</div>
                  </div>
                  <div class="receipt-footer" v-if="receiptSettings.footer">
                    {{ receiptSettings.footer }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 界面偏好设置 -->
        <el-tab-pane label="界面偏好" name="interface">
          <el-form :model="interfaceSettings" label-width="120px" v-loading="loading.interface">
            <el-form-item label="界面主题">
              <el-radio-group v-model="interfaceSettings.theme">
                <el-radio label="light">明亮模式</el-radio>
                <el-radio label="dark">暗黑模式</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="主题颜色">
              <el-color-picker v-model="interfaceSettings.primaryColor" />
            </el-form-item>
            

            
            <el-form-item label="列表显示密度">
              <el-radio-group v-model="interfaceSettings.density">
                <el-radio label="default">默认</el-radio>
                <el-radio label="medium">中等</el-radio>
                <el-radio label="small">紧凑</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="默认首页">
              <el-select v-model="interfaceSettings.defaultPage">
                <el-option label="POS收银" value="/pos" />
                <el-option label="订单管理" value="/orders" />
                <el-option label="商品管理" value="/products" />
                <el-option label="报表" value="/reports" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="通知设置">
              <el-checkbox v-model="interfaceSettings.notifications.inventory">库存预警通知</el-checkbox>
              <el-checkbox v-model="interfaceSettings.notifications.orders">新订单通知</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveInterfaceSettings">保存设置</el-button>
              <el-button @click="resetInterfaceSettings">恢复默认</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { updateSettings } from '@/api/systemSettings';
import configService from '@/utils/configService';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

// 当前激活的标签页
const activeTab = ref('store');

// 加载状态
const loading = reactive({
  store: false,
  receipt: false,
  interface: false
});

// 店铺信息设置 - 使用configService中的数据
const storeSettings = configService.getStoreSettings();

// 小票打印设置 - 使用configService中的数据
const receiptSettings = configService.getReceiptSettings();

// 界面偏好设置 - 使用configService中的数据
const interfaceSettings = configService.getInterfaceSettings();

// 获取认证头信息
const getAuthHeaders = () => {
  const token = localStorage.getItem('token');
  if (token) {
    return { Authorization: `Bearer ${token}` };
  }
  return {};
};

// 获取API基础URL
const getApiUrl = (path) => {
  const baseUrl = '/api'; // 使用相对路径，避免跨域问题
  return `${baseUrl}${path}`;
};

// 保存店铺信息设置
const saveStoreSettings = async () => {
  loading.store = true;
  try {
    // 安全处理时间格式
    let openTimeValue = '';
    let closeTimeValue = '';
    
    if (storeSettings.openTime) {
      if (typeof storeSettings.openTime === 'string') {
        openTimeValue = storeSettings.openTime;
      } else if (storeSettings.openTime instanceof Date && !isNaN(storeSettings.openTime)) {
        // 确保是有效的Date对象
        openTimeValue = `${String(storeSettings.openTime.getHours()).padStart(2, '0')}:${String(storeSettings.openTime.getMinutes()).padStart(2, '0')}`;
      }
    }
    
    if (storeSettings.closeTime) {
      if (typeof storeSettings.closeTime === 'string') {
        closeTimeValue = storeSettings.closeTime;
      } else if (storeSettings.closeTime instanceof Date && !isNaN(storeSettings.closeTime)) {
        // 确保是有效的Date对象
        closeTimeValue = `${String(storeSettings.closeTime.getHours()).padStart(2, '0')}:${String(storeSettings.closeTime.getMinutes()).padStart(2, '0')}`;
      }
    }
    
    const settingsData = {
      name: storeSettings.name,
      location: storeSettings.location,
      address: storeSettings.address,
      phone: storeSettings.phone,
      openTime: openTimeValue,
      closeTime: closeTimeValue,
      taxNumber: storeSettings.taxNumber,
      slogan: storeSettings.slogan,
      qrCodeUrl: storeSettings.qrCodeUrl
    };
    
    const response = await updateSettings('frontend.store', settingsData);
    if (response.success) {
      ElMessage.success('店铺信息设置保存成功');
      // 重新加载店铺设置到configService
      await configService.loadStoreSettings();
    } else {
      ElMessage.error('店铺信息设置保存失败');
    }
  } catch (error) {
    console.error('保存店铺信息设置失败:', error);
    ElMessage.error('保存店铺信息设置失败');
  } finally {
    loading.store = false;
  }
};

// 重置店铺信息设置
const resetStoreSettings = () => {
  storeSettings.name = '哈喽啤鲜生';
  storeSettings.location = '国贸360店';
  storeSettings.address = '北京市朝阳区国贸中心';
  storeSettings.phone = '010-12345678';
  storeSettings.openTime = '';
  storeSettings.closeTime = '';
  storeSettings.taxNumber = '';
  storeSettings.slogan = '精酿啤酒，鲜活生活';
  storeSettings.qrCodeUrl = ''; // 重置二维码URL
  
  ElMessage.success('店铺信息设置已重置');
};

// 保存小票打印设置
const saveReceiptSettings = async () => {
  loading.receipt = true;
  try {
    const settingsData = {
      width: receiptSettings.width,
      fontSize: receiptSettings.fontSize,
      header: receiptSettings.header,
      footer: receiptSettings.footer,
      printLogo: String(receiptSettings.printLogo),
      printQrCode: String(receiptSettings.printQrCode),
      printOrderNumber: String(receiptSettings.printOrderNumber),
      productDisplay: receiptSettings.productDisplay
    };
    
    const response = await updateSettings('frontend.receipt', settingsData);
    if (response.success) {
      ElMessage.success('小票打印设置保存成功');
      // 重新加载小票设置到configService
      await configService.loadReceiptSettings();
    } else {
      ElMessage.error('小票打印设置保存失败');
    }
  } catch (error) {
    console.error('保存小票打印设置失败:', error);
    ElMessage.error('保存小票打印设置失败');
  } finally {
    loading.receipt = false;
  }
};

// 打印测试小票
const printTestReceipt = () => {
  ElMessage.success('测试小票打印请求已发送');
  // 这里需要调用打印API
};

// 重置小票打印设置
const resetReceiptSettings = async () => {
  try {
    // 重置为数据库中的默认值
    const defaultSettings = {
      width: '58',
      fontSize: 'medium',
      header: '哈喽啤鲜生国贸店',
      footer: '谢谢惠顾，欢迎再次光临！',
      printLogo: 'true',
      printQrCode: 'true',
      printOrderNumber: 'true',
      productDisplay: 'simple'
    };

    // 保存默认设置到数据库
    const response = await updateSettings('frontend.receipt', defaultSettings);
    if (response.success) {
      // 重新加载设置
      await configService.loadReceiptSettings();
      ElMessage.success('小票打印设置已重置');
    } else {
      ElMessage.error('重置小票打印设置失败');
    }
  } catch (error) {
    console.error('重置小票打印设置失败:', error);
    ElMessage.error('重置小票打印设置失败');
  }
};

// 保存界面偏好设置
const saveInterfaceSettings = async () => {
  loading.interface = true;
  try {
    const settingsData = {
      theme: interfaceSettings.theme,
      primaryColor: interfaceSettings.primaryColor,
      density: interfaceSettings.density,
      defaultPage: interfaceSettings.defaultPage,
      'notifications.inventory': String(interfaceSettings.notifications.inventory),
      'notifications.orders': String(interfaceSettings.notifications.orders)
    };
    
    const response = await updateSettings('frontend.interface', settingsData);
    if (response.success) {
      ElMessage.success('界面偏好设置保存成功');
      
      // 保存到localStorage并应用设置
      configService.saveInterfaceSettingsToLocal();
      configService.applyInterfaceSettings();
      
      // 重新加载界面设置到configService
      await configService.loadInterfaceSettings();
    } else {
      ElMessage.error('界面偏好设置保存失败');
    }
  } catch (error) {
    console.error('保存界面偏好设置失败:', error);
    ElMessage.error('保存界面偏好设置失败');
  } finally {
    loading.interface = false;
  }
};

// 重置界面偏好设置
const resetInterfaceSettings = () => {
  interfaceSettings.theme = 'light';
  interfaceSettings.primaryColor = '#409EFF';
  interfaceSettings.density = 'default';
  interfaceSettings.defaultPage = '/pos';
  interfaceSettings.notifications.inventory = true;
  interfaceSettings.notifications.orders = true;
  
  // 应用默认主题
  configService.applyInterfaceSettings();
  
  ElMessage.success('界面偏好设置已重置');
};

// 监听界面设置变化，实时应用
watch(
  () => [
    interfaceSettings.theme,
    interfaceSettings.primaryColor,
    interfaceSettings.density
  ],
  () => {
    configService.applyInterfaceSettings();
  },
  { deep: true }
);

// 二维码上传成功处理
const handleQrCodeSuccess = (response) => {
  if (response.status === 'success') {
    storeSettings.qrCodeUrl = response.data.url;
    ElMessage.success('二维码上传成功');
    // 立即保存设置到数据库
    saveStoreSettings();
  } else {
    ElMessage.error(response.message || '二维码上传失败');
  }
};

// 二维码上传前检查
const beforeQrCodeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传JPG或PNG格式的图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};

// 删除二维码
const removeQrCode = () => {
  storeSettings.qrCodeUrl = '';
  ElMessage.success('二维码已删除');
};

// 初始化
onMounted(async () => {
  // 确保configService已经初始化
  if (!configService.isInitialized()) {
    await configService.init();
  }
});
</script>

<style scoped>
.settings-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.time-separator {
  margin: 0 10px;
}

/* 小票预览样式 */
.receipt-settings-container {
  display: flex;
  gap: 20px;
}

.receipt-form {
  flex: 1;
}

.receipt-preview {
  flex: 1;
  max-width: 300px;
}

.receipt-preview h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.receipt-preview-container {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  max-width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.receipt-mock {
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
  text-align: center;
}

.receipt-header, .receipt-footer {
  margin: 10px 0;
  font-size: 10px;
}

.receipt-title {
  font-size: 14px;
  font-weight: bold;
  margin: 10px 0;
}

.receipt-info {
  margin: 10px 0;
  font-size: 10px;
}

.receipt-items {
  margin: 10px 0;
  text-align: left;
}

.receipt-item-header, .receipt-item {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px dashed #dcdfe6;
  padding: 5px 0;
}

.receipt-item-header {
  font-weight: bold;
}

.receipt-total {
  margin: 10px 0;
  text-align: right;
  font-weight: bold;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .receipt-settings-container {
    flex-direction: column;
  }
  
  .receipt-preview {
    max-width: 100%;
  }
}

/* 二维码上传样式 */
.qrcode-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.qrcode-uploader:hover {
  border-color: #409EFF;
}

.qrcode-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.qrcode-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.qrcode-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.qrcode-uploader:hover .qrcode-overlay {
  opacity: 1;
}

.qrcode-change-icon {
  font-size: 20px;
  margin-bottom: 5px;
}

.qrcode-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.qrcode-actions {
  margin-top: 10px;
  text-align: center;
}
</style> 